package com.example.idlefish.GoodsInfo

import android.Manifest
import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Context
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.graphics.Typeface
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.provider.MediaStore
import android.provider.Settings
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import android.widget.ImageView
import android.widget.Switch
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.idlefish.GoodsInfo.ActivityContract.BaiduMapActivityContract
import com.example.idlefish.GoodsInfo.ActivityContract.PickPhotoActivityContract
import com.example.idlefish.GoodsInfo.ActivityContract.TakePhotoActivityContract
import com.example.idlefish.GoodsInfo.parseGson.parseClassification
import com.example.idlefish.GoodsInfo.pojo.Classification
import com.example.idlefish.GoodsInfo.pojo.Property
import com.example.idlefish.GoodsInfo.pojo.PropertyValue
import com.example.idlefish.GoodsInfo.pojo.InsertGoodInfo
import com.example.idlefish.PublicModule.ApplicationConst
import com.example.idlefish.PublicModule.UserConst
import com.example.idlefish.R
import com.example.idlefish.databinding.ActivityCreateGoodBinding
import com.google.android.material.bottomsheet.BottomSheetDialog
import okhttp3.Call
import okhttp3.Callback
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.Response
import org.json.JSONArray
import org.json.JSONObject
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.IOException
import java.util.Calendar
import java.util.Collections
import kotlin.concurrent.thread
import kotlin.math.min
import kotlin.random.Random


class CreateGoodActivity : AppCompatActivity() {
    private lateinit var binding:ActivityCreateGoodBinding
    var alertDialog: AlertDialog? = null
    private val server_ip = ApplicationConst.server_ip
    private var mFilePath = ""
    private lateinit var mFileUri:Uri
    //只包含在服务区中的文件名 不包括后缀的 统一.jpeg
    private val piclst_net = ArrayList<String>()
    private val piclst_local = ArrayList<Uri>()
    private lateinit var  adapter:goodPicAdapter
    private lateinit var classifyAdapter:GoodClassifyAdapter
    private lateinit var propertyAdapter:PropertyAdapter
    private lateinit var valueAdapter:ValuesAdapter

    private lateinit var bottomSheetDialog : BottomSheetDialog
    private lateinit var bottomSheetExport2 : BottomSheetDialog
    private lateinit var bottomSheetDeleteImage : BottomSheetDialog
    private val keywords = ArrayList<String>()
    private val keywordToClassify = mutableMapOf<String, MutableList<String>>()

    //商品分类的list
    private val lstclassification = ArrayList<Classification>()
    //当前选择的商品分类编号
    private var goodClassifyIndex = 0
    //当前分类的所有属性信息
    private val lstProperty = ArrayList<Property>()
    //用户选定的商品的属性 和 属性值
    private var goodValuePair = mutableMapOf<Int, Int>()

    private val handler = Handler(Looper.getMainLooper())
    private val delayMills = 800L
    private lateinit var bottomView:View
    private lateinit var bottomExportView:View
    private lateinit var bottomSheetDeleteImageView : View
    private var pickPhotoLauncher = registerForActivityResult(PickPhotoActivityContract()){
        result->
        if(result != Uri.EMPTY)
        {
            val bitmap = getBitmapFromUri(this, result)
            bitmap?.let { momoImage(it) }
        }
    }
    private var takePhotoLauncher = registerForActivityResult(TakePhotoActivityContract()){
            result->
        if(result)
        {
            val bitmap = getBitmapFromUri(this, mFileUri)
            bitmap?.let { momoImage(it) }
        }
        else
        {
            Toast.makeText(this, "操作失败", Toast.LENGTH_LONG).show()
        }
    }

    private var mapLauncher = registerForActivityResult(BaiduMapActivityContract()){
        result->
            if (result == null || result =="")
                binding.address.text = " "
            else
                binding.address.text = result
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityCreateGoodBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.loading.hide()
        binding.loadingtv.visibility = View.GONE

        getPermission()
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams. SOFT_INPUT_ADJUST_PAN);
        binding.lstClassify.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        classifyAdapter = GoodClassifyAdapter(lstclassification)
        binding.lstClassify.adapter = classifyAdapter


        binding.lstpic.layoutManager = GridLayoutManager(this, 3)
        adapter = goodPicAdapter(piclst_local)
        binding.lstpic.adapter = adapter

        binding.lstProperty.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        propertyAdapter = PropertyAdapter(lstProperty)
        binding.lstProperty.adapter = propertyAdapter

        bottomSheetDeleteImage = BottomSheetDialog(this, R.style.BottomSheetDialog)
        bottomSheetDialog = BottomSheetDialog(this, R.style.BottomSheetDialog)
        //将底部的视图绑定到这个变量,方便找到.
        keywordToClassify.apply {
            put("车", mutableListOf("车", "二手车", "排放量", ))
            put("书籍", mutableListOf("小说", "书", "小学", "幼儿园", "教辅"))
            put("玩具", mutableListOf("捏捏", "儿童", "幼儿", "玩具", "毛绒", "早教", "积木"))
            put("陪伴服务", mutableListOf("陪诊", "健身房", "陪练", "练车", "陪学", "技术", "上分"))
            put("约拍", mutableListOf("本地", "底片", "送片", "妆发", "接", "跟拍"))
            put("维修", mutableListOf("维修", "管道"))
            put("宠", mutableListOf("猫", "狗", "鱼", "虫", "仓鼠", "异宠物", "宠物", "宠", "豚鼠"))
            put("快递代发", mutableListOf("快递", "寄", "货"))
            put("运动", mutableListOf("鞋", "跳绳", "跑", "跳", "阿迪", "耐克"))
            put("二次元", mutableListOf("二次元", "樱", "切煤", "吧唧", "色纸", "b", "手办", "初音", "ACG", "lo", "手办"))
            put("音乐", mutableListOf("霉霉", "黑胶", "唱片", "音", "唱", "歌", "Taylor", "CD", "专辑"))
            put("练", mutableListOf("学车", "陪练", "王者", "原神", "铲", "代练", "吃鸡", "陪", "练", "羽毛球", "网球", "乒乓球"))
            put("摄影", mutableListOf("写真", "代拍", "跟拍", "COS", "婚纱", "结婚", "影"))
            put("券", mutableListOf("代金券", "元", "券"))
            put("代", mutableListOf("代", "券", "王者", "原神", "铲"))
            put("盲盒", mutableListOf("泡泡玛特", "福袋", "盲盒", "LABUBU", "DIMO"))
            put("票", mutableListOf("日", "月", "票", "景点", "演唱会", "音乐节", "电影", "场"))
            put("王者", mutableListOf("代", "貂蝉", "李白", "杨玉环", "车", "r", "星", "英雄"))
            put("潮", mutableListOf("潮牌", "巴黎世家", "LV", "宝格丽", "阿玛尼", "lv", "nike", "yeezy"))
            put("动漫", mutableListOf("动漫", "手办", "吧唧", "立牌", "纪念钞","周边"))
            put("裙", mutableListOf("裙"))
            put("玉石", mutableListOf("玉", "石"))
            put("面", mutableListOf("水", "霜", "乳"))
            put("文化", mutableListOf("文创", "文", "创"))
            put("户外", mutableListOf("登山", "户外", "冲锋衣"))

        }
        bottomSheetExport2 = BottomSheetDialog(this, R.style.BottomSheetDialog)
        bottomView = LayoutInflater.from(this).inflate(R.layout.bottom_sheet_layout, null, false)
        bottomExportView = LayoutInflater.from(this).inflate(R.layout.bottom_sheet_export_ayout, null, false)
        bottomSheetDeleteImageView = LayoutInflater.from(this).inflate(R.layout.bottom_sheet_picdelete_layout, null, false)
        ////baoc //是否保存草稿
        binding.end.setOnClickListener {

            finish()
        }
        binding.Send.setOnClickListener {
            binding.loadingtv.visibility = View.VISIBLE
            binding.loading.show()
            if (UserConst.id == -1L)
            {
                Toast.makeText(applicationContext, "请先登录再发送商品", Toast.LENGTH_LONG)
            }
            else{
                val info =  binding.goodText.text.toString()
                val tepIndex = info.indexOf("\n")
                var name = ""
                val jsp = "http://${server_ip}:8080/insertGood"
                if(tepIndex == -1 || tepIndex > 20)
                {
                    name = info.substring(0, min(25, info.length))
                }
                else
                {
                    name = info.substring(0, tepIndex);
                }
                val address  = binding.address.text.toString()
                var kind = 15L
                if(lstclassification.isNotEmpty())
                    kind = lstclassification[goodClassifyIndex].classifyId ?: 15
                val propertyAndValue = ArrayList<Long>()
                for((key, value) in goodValuePair)
                {
                    propertyAndValue.add(lstProperty[key].propertyValue[value].id)
                }
                val price =  binding.price.text.toString().toFloat()
                val ExportWay = binding.exportWay.text.toString()
                var post_method = 0
                var post_price = 0
                if(ExportWay.contains("包邮")){
                    post_method = ApplicationConst.post_method.BAOYOU.value
                }
                else if(ExportWay.contains("按距离计费")){
                    post_method = ApplicationConst.post_method.ANJULI.value
                    post_price = ExportWay.substring(ExportWay.lastIndexOf("¥")+1).toInt()
                    Log.d("post_price", post_price.toString())
                }
                else if(ExportWay.contains("一口价")) {
                    post_method = ApplicationConst.post_method.YIKOUJIA.value
                    post_price = ExportWay.substring(ExportWay.lastIndexOf("¥")+1).toInt()
                }
                else if(ExportWay.contains("无需邮寄")) {
                    post_method = ApplicationConst.post_method.WUXUYOUJI.value
                }
                var self_get = false
                val advantages = arrayListOf("回复超快", "卖家信用极好", "百分百好评")
                val advantage = advantages[Random.nextInt(advantages.size)]
                if(ExportWay.contains("自提"))
                    self_get = true
                if(info.length < 10)
                {
                    Toast.makeText(this, "商品描述不可少于十个字", Toast.LENGTH_LONG).show()
                }
                else if(price > 2147483647 || price < 0 || price.toInt() == 0)
                {
                    Toast.makeText(this, "请填写合理的价格", Toast.LENGTH_LONG).show()
                }
                else{
                    val insertGoodInfo = InsertGoodInfo(info, name, piclst_net, address, kind, propertyAndValue, price, post_method, self_get, post_price, UserConst.id, advantage)
                    Log.d("insertGood", insertGoodInfo.toString())
                    goodInsertNetRequest(insertGoodInfo, jsp, object : Callback{
                        override fun onFailure(call: Call, e: IOException) {
                            Log.d("goodInfo", "传递商品信息失败")
                            runOnUiThread {
                                binding.loading.hide()
                                binding.loadingtv.visibility = View.GONE
                                Toast.makeText(applicationContext, "上传失败，请再次重试", Toast.LENGTH_SHORT).show()
                            }
                        }
                        //汽车
                        override fun onResponse(call: Call, response: Response) {
                            //val picAddress = response.body?.string()
                            val responseBody = response.body?.string()
                            try{
                                // Log.d("success", "我发了别赖我汽车")
                                val goodId = responseBody?.toLong()
                                ///当goodId传-1的时候 新增失败

                                runOnUiThread {
                                    binding.loadingtv.visibility = View.GONE
                                    binding.loading.hide()
                                    Toast.makeText(applicationContext, "上传成功", Toast.LENGTH_SHORT).show()
                                    val intent = Intent()
                                    intent.putExtra("goodId", goodId)
                                    setResult(RESULT_OK,intent)
                                    finish()
                                }
                            }catch(e:NumberFormatException){
                                e.printStackTrace()
                                Log.e("createGoodAcitivity", "转换goodId失败了")
                            }
                        }
                    })
                }
                binding.loadingtv.visibility = View.GONE
                binding.loading.hide()
            }
        }
        //监控对商品的描述
        binding.goodText.addTextChangedListener(object :  TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                //移除所有关联任务
                handler.removeCallbacksAndMessages(null)
                //安排一个延迟任务
                handler.postDelayed({
                    //再次查找关键字 放没有的进去
                    if(s != null)
                        findKeywords(keywords, s.toString())
                    //每次网络请求都是把整个text里的keyword都去数据库里找一遍  返回Classification类
                    if(keywords.isNotEmpty())
                    {
                        classifyNetReqest(keywords, object : Callback{
                            override fun onFailure(call: Call, e: IOException) {
                                Log.d("hello", "网络请求商品分类失败")
                            }

                            override fun onResponse(call: Call, response: Response) {
                                val responseData = response.body?.string().toString()
                                val results = parseClassification.parseClassification(responseData)
                                for(tep in results)
                                {
                                    if(!lstclassification.contains(tep))
                                    {
                                        lstclassification.add(tep)
                                    }
                                }
                                runOnUiThread {
                                    classifyAdapter.notifyDataSetChanged()
                                }
                                Log.d("hello", responseData)
                            }
                        })
                    }
                 }, delayMills)
            }
        })
        binding.end.setOnClickListener {
            val intent = Intent()
            //intent.putExtra("info", Good(1, "你好你好", "dsdadsa", 12.3f, null))
//            setResult(RESULT_OK, intent)
//            finish()
        }
        binding.address.setOnClickListener {
            mapLauncher.launch(Unit)
        }


        binding.export.setOnClickListener {
            bottomSheetExport2.setContentView(bottomExportView)
            bottomSheetExport2.show()
            val way1 = bottomExportView.findViewById<View>(R.id.pop1)
            val way2 = bottomExportView.findViewById<View>(R.id.pop2)
            val way3 = bottomExportView.findViewById<View>(R.id.pop3)
            val way4 = bottomExportView.findViewById<View>(R.id.pop4)
            val but1 = bottomExportView.findViewById<CheckBox>(R.id.freeExport)
            val but2 = bottomExportView.findViewById<CheckBox>(R.id.discharge)
            val but3 = bottomExportView.findViewById<CheckBox>(R.id.onetime)
            val but4 = bottomExportView.findViewById<CheckBox>(R.id.noExport)
            val exitted = bottomExportView.findViewById<ImageView>(R.id.popWindowDele)
            val switch = bottomExportView.findViewById<Switch>(R.id.switcher)
            val confirmButton = bottomExportView.findViewById<Button>(R.id.popwindowConfiure)
            val post_price = bottomExportView.findViewById<EditText>(R.id.yikoujiaPrice)
            but1.setOnClickListener {
                but2.isChecked = false
                but3.isChecked = false
                but4.isChecked = false
                but1.isChecked = true
            }
            but2.setOnClickListener {
                but1.isChecked = false
                but3.isChecked = false
                but4.isChecked = false
                but2.isChecked = true
            }
            but3.setOnClickListener{
                but1.isChecked = false
                but2.isChecked = false
                but4.isChecked = false
                but3.isChecked = true
            }
            but4.setOnClickListener {
                but1.isChecked = false
                but2.isChecked = false
                but3.isChecked = false
                but4.isChecked = true
            }
            way1.setOnClickListener{
                but2.isChecked = false
                but3.isChecked = false
                but4.isChecked = false
                but1.isChecked = true
            }
            way2.setOnClickListener{
                but1.isChecked = false
                but3.isChecked = false
                but4.isChecked = false
                but2.isChecked = true
            }
            way3.setOnClickListener{
                but1.isChecked = false
                but2.isChecked = false
                but4.isChecked = false
                but3.isChecked = true

            }
            way4.setOnClickListener{
                but1.isChecked = false
                but2.isChecked = false
                but3.isChecked = false
                but4.isChecked = true
            }
            exitted.setOnClickListener {
                bottomSheetExport2.dismiss()
            }
            confirmButton.setOnClickListener {
                var address = ""
                if(switch.isChecked)
                {
                    if(address != "")
                    {
                        address += "/"
                    }
                    address += "自提"
                }
                if (but1.isChecked)
                {
                    if(address != "")
                    {
                        address += "/"
                    }
                    address += "包邮"
                }
                else if(but2.isChecked)
                {
                    if(address != "")
                    {
                        address += "/"
                    }
                    address += "按距离计费 ¥12"
                }
                else if(but3.isChecked)
                {
                    if(address != "")
                    {
                        address += "/"
                    }
                    val price = post_price.text.toString().toInt()
                    address += "一口价 ¥${price}"
                }
                else if(but4.isChecked)
                {
                    if(address != "")
                    {
                        address += "/"
                    }
                    address += "无需邮寄"
                }
                binding.exportWay.text = address
                bottomSheetExport2.dismiss()
            }
        }
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

    }
    fun goodInsertNetRequest(goodInfo: InsertGoodInfo, jsp:String, callback: Callback)
    {
        thread {
            val client =  OkHttpClient()
            goodInfo.propertyAndValue.sort()
            val requestBodyJson = JSONObject().apply {
                put("userId", goodInfo.userId)
                put("info", goodInfo.info)
                put("name", goodInfo.name)
                put("piclist", JSONArray(goodInfo.piclist))
                put("address", goodInfo.address)
                put("kind", goodInfo.kind)
                put("propertyAndValue", JSONArray(goodInfo.propertyAndValue))
                put("price", goodInfo.price)
                put("post_method", goodInfo.post_method)
                put("self_get", goodInfo.self_get)
                put("post_price", goodInfo.post_price)
                put("advantage", goodInfo.advantage)
            }.toString()
            Log.d("netRequest", requestBodyJson)
            val requestBody = RequestBody.create("application/json;charset=utf-8".toMediaType(), requestBodyJson)
            val request = Request.Builder()
                .url(jsp)
                .post(requestBody)
                .build()
            client.newCall(request).enqueue(callback)
        }
    }



    fun momoImage(bitmap:Bitmap)
    {
        val newbitmap = bitmap?.let { zipBitmap(it,  0.5f) }
        val fileName = "IMG"+Calendar.getInstance().time + ".jpeg"
        val newImageUri = Uri.parse(MediaStore.Images.Media.insertImage(contentResolver, newbitmap, fileName,null))
        //把压缩的图片存到媒体库
        piclst_local.add(newImageUri)
        newbitmap?.let {
            ApplicationConst.uploadImage(it, object : Callback{
                override fun onFailure(call: Call, e: IOException) {
                    Log.d("picInfo", "上传图片失败")
                }

                override fun onResponse(call: Call, response: Response) {
                    Log.d("picInfo", "上传图片成功")
                    val picAddress = response.body?.string()
                    if(picAddress != null)
                    {
                        piclst_net.add(picAddress)
                    }
                }
            }, fileName)
        }
        adapter.notifyDataSetChanged()
    }
    /* fun uploadImage(bitmap: Bitmap, callback: Callback, fileName:String)
    {
        thread {
            val byteArray = bitmapToByteArray(bitmap)
            val requestBody = RequestBody.create("image/jpeg".toMediaTypeOrNull(), byteArray)
            //这里的"image"相当于对应后端http请求的那个接口的字段名public String uploadImage(@RequestParam("image")MultipartFile image)
            val part = MultipartBody.Part.createFormData("image", fileName, requestBody)
            val client=OkHttpClient()
            val request = Request.Builder()
                .url("http://${server_ip}:8080/uploadImage")
                .header("Content-Type", "multipart/form-data")
                .post(MultipartBody.Builder().setType(MultipartBody.FORM).addPart(part).build())
                .build()
            client.newCall(request).enqueue(callback)
        }
        //汽车汽车哎呦哎呦想吃甜甜的山药豆
    }
    fun bitmapToByteArray(bitmap: Bitmap):ByteArray{
        val outputStream = ByteArrayOutputStream()
        //将位图压缩为指定的byteArray
        bitmap.compress(Bitmap.CompressFormat.JPEG,100, outputStream)
        return outputStream.toByteArray()
    } */
    fun classifyNetReqest(keywords:ArrayList<String>, callback: Callback)
    {
        val jsp = "http://${server_ip}:8080/getClassifyByKeyWord"
        thread {
            val client = OkHttpClient()
            val Params = StringBuilder().apply{
                if(keywords.isNotEmpty()){
                    for((index, keyword) in keywords.withIndex()){
                        if(index > 0) append("&")
                        append("keyword=").append(keyword)
                    }
                }
            }.toString()
            val url = "${jsp}?${Params}"
            val request = Request.Builder().url(url).get().build()
            client.newCall(request).enqueue(callback)
        }
    }
    private fun findMatchKey(input:String, map:Map<String, List<String>>):ArrayList<String>
    {
        val matchKeys = ArrayList<String>()
        for((key, value) in map){
            if(value.any{input.contains(it, ignoreCase = true)}){
                matchKeys.add(key)
            }
        }
        return matchKeys
    }
    fun findKeywords(lstKeyword:ArrayList<String>, text:String)
    {
        if (text == "") {
            return
        }
        if(lstKeyword.isEmpty()){
            lstKeyword.add("其他闲置")
            goodClassifyIndex = 0
        }
        //重新查一次
        val matchKey = findMatchKey(text, keywordToClassify)
        //不包含的放进去
        for(tep in matchKey)
        {
            if(!lstKeyword.contains(tep))
                lstKeyword.add(tep)
        }
    }
    private class PropertyValueViewHolder(view:View):RecyclerView.ViewHolder(view){
        val tvValue: TextView = view.findViewById(R.id.tvClassify)
    }
    private inner class ValuesAdapter(val lstValues:List<PropertyValue>, val propertyIndex:Int):RecyclerView.Adapter<PropertyValueViewHolder>(){
        //每一个listAdapter都有一个选择的index记录 别混淆了  每一个也有唯一的propertyIndex 这都是一个实例
        var selectedIndex = -1
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PropertyValueViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.good_classify_layout, parent, false)
            val viewHolder = PropertyValueViewHolder(view)
            viewHolder.tvValue.setOnClickListener {

                viewHolder.tvValue.isSelected = true
                val index = viewHolder.absoluteAdapterPosition
                selectedIndex = index
                goodValuePair[propertyIndex] = index
                //一个属性就一个 你还想怎么样
                notifyDataSetChanged()
            }
            return viewHolder
        }

        override fun onBindViewHolder(holder: PropertyValueViewHolder, position: Int) {
            holder.tvValue.text = lstValues[position].name
            holder.tvValue.isSelected = (selectedIndex == position)
            if(selectedIndex == position)
            {
                holder.tvValue.setTypeface(null, Typeface.BOLD)
                holder.tvValue.setTextColor(android.graphics.Color.BLACK)

            }
            else
            {
                holder.tvValue.setTypeface(null, Typeface.NORMAL)
                holder.tvValue.setTextColor(android.graphics.Color.DKGRAY)

            }
        }

        override fun getItemCount(): Int {
            return lstValues.size
        }
    }
    private class PropertyViewHolder(view:View):RecyclerView.ViewHolder(view){
        val tvPropertyName = view.findViewById<TextView>(R.id.tvPropertyName)
        val lstPropertyValue = view.findViewById<RecyclerView>(R.id.lstProertyValue)
    }
    inner private class PropertyAdapter(val lstProperty: ArrayList<Property>):RecyclerView.Adapter<PropertyViewHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PropertyViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.good_property_layout, parent, false)
            val viewHolder = PropertyViewHolder(view)
            viewHolder.lstPropertyValue.layoutManager = LinearLayoutManager(applicationContext, LinearLayoutManager.HORIZONTAL, false)
            return viewHolder
        }
//每一个value列表都有一个对应的adapter
        override fun onBindViewHolder(holder: PropertyViewHolder, position: Int) {
            holder.tvPropertyName.text = lstProperty[position].propertyName
            valueAdapter = ValuesAdapter(lstProperty[position].propertyValue, position)
            holder.lstPropertyValue.adapter = valueAdapter
          }

        override fun getItemCount(): Int {
            return lstProperty.size
        }
    }
    private class classifyViewHHolder(view:View):RecyclerView.ViewHolder(view){
        val tvClassify = view.findViewById<TextView>(R.id.tvClassify)
    }
    inner private class GoodClassifyAdapter(val classlst:ArrayList<Classification>):RecyclerView.Adapter<classifyViewHHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): classifyViewHHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.good_classify_layout, parent, false)
            val viewHolder = classifyViewHHolder(view)
            viewHolder.tvClassify.setOnClickListener {
                val index = viewHolder.absoluteAdapterPosition
                goodClassifyIndex = index
                goodValuePair.clear()
                lstProperty.clear()
                lstProperty.addAll(classlst[index].properties)
                classifyAdapter.notifyDataSetChanged()
                propertyAdapter.notifyDataSetChanged()
            }
            return viewHolder
        }

        @SuppressLint("NotifyDataSetChanged")
        override fun onBindViewHolder(holder: classifyViewHHolder, position: Int) {
            holder.tvClassify.text = classlst[position].classifyName
            holder.tvClassify.isSelected = (position == goodClassifyIndex)
            if(goodClassifyIndex == position)
            {
                holder.tvClassify.setTypeface(null, Typeface.BOLD)
                holder.tvClassify.setTextColor(android.graphics.Color.BLACK)

            }
            else
            {
                holder.tvClassify.setTypeface(null, Typeface.NORMAL)
                holder.tvClassify.setTextColor(android.graphics.Color.DKGRAY)

            }
        }

        override fun getItemCount(): Int {
            return classlst.size
        }

    }
    private class picviewHolder(view: View):RecyclerView.ViewHolder(view){
        val tvPic = view.findViewById<ImageView>(R.id.ivgoodPic)
    }
    inner private class goodPicAdapter(val piclst:ArrayList<Uri>):RecyclerView.Adapter<picviewHolder>(){

        override fun getItemCount(): Int {
            if(piclst.size <= 8)
                return piclst.size + 1;
            else
                return 9;
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): picviewHolder {
            // 将文件布局添加到视图 创建视图
            //LayoutInflater  从XML创建视图的工具                                                将新创建的视图添加到parent  false表示不是立即附加
            val view = LayoutInflater.from(parent.context).inflate(R.layout.good_pic_layout, parent, false)
            val viewHolder = picviewHolder(view)
            viewHolder.itemView.setOnClickListener {
                val index = viewHolder.absoluteAdapterPosition
                if(index < piclst_local.size)
                {
                    bottomSheetDeleteImage.setContentView(bottomSheetDeleteImageView)
                    bottomSheetDeleteImage.show()
                    val yess = bottomSheetDeleteImageView.findViewById<Button>(R.id.dele_true)
                    val noo = bottomSheetDeleteImageView.findViewById<Button>(R.id.popwindowCancel)
                    val cancel = bottomSheetDeleteImageView.findViewById<TextView>(R.id.popwindowCancel)
                    yess.setOnClickListener {
                        val dele_Address = piclst_net[index]
                        deleteImageOnNet(dele_Address, object : Callback{
                            override fun onFailure(call: Call, e: IOException) {
                                Log.d("picdelete", "网络错误 删除图片的事情免谈")
                            }

                            override fun onResponse(call: Call, response: Response) {
                                Log.d("picdelete", "网络is no problem")
                                val sucess = response.body?.string()
                                if(sucess == "true")
                                {
                                    runOnUiThread {
                                        piclst_net.removeAt(index)
                                        piclst_local.removeAt(index)
                                        notifyDataSetChanged()
                                    }
                                }
                                else
                                {
                                    Log.d("picdelete", "这次是你后端删除失败了,一切都免谈")
                                }
                            }
                        })
                        bottomSheetDeleteImage.dismiss()
                    }
                    noo.setOnClickListener {
                        bottomSheetDeleteImage.dismiss()
                    }
                    cancel.setOnClickListener{
                        bottomSheetDeleteImage.dismiss()
                    }
                }
                else
                {
                    bottomSheetDialog.setContentView(bottomView)
                    bottomSheetDialog.show()
                    val takePhoto = bottomView.findViewById<View>(R.id.check_photo)
                    val cancel = bottomView.findViewById<View>(R.id.cancel)
                    val choosePic = bottomView.findViewById<View>(R.id.choose_photo)
                    takePhoto.setOnClickListener {
                        bottomSheetDialog.dismiss()
                        openCamera()
                    }
                    choosePic.setOnClickListener {
                        bottomSheetDialog.dismiss()
                        pickPhotoLauncher.launch(Unit)
                    }
                    cancel.setOnClickListener{
                        bottomSheetDialog.dismiss()
                    }
                }
            }
            return viewHolder
        }

        override fun onBindViewHolder(holder: picviewHolder, position: Int) {
            if(position != piclst.size)
                holder.tvPic.setImageURI(piclst[position])
            else
                holder.tvPic.setImageResource(R.drawable.good_more_pic)
        }

    }
    fun getBitmapFromUri(context: Context, uri: Uri): Bitmap? {
        return try {
            context.contentResolver.openInputStream(uri)?.use { inputStream ->
                BitmapFactory.decodeStream(inputStream)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }
    //请求返回的是图片的绝对路径
    //b2a800c1-e319-480c-aa28-aa3af355d22d
    fun deleteImageOnNet(ImageAddress:String, callback: Callback){
        val client = OkHttpClient()
        val jsp = "http://${server_ip}:8080/deleteImage?imageAddress=${ImageAddress}"
        val request = Request.Builder()
            .url(jsp).delete().build()
        client.newCall(request).enqueue(callback)
    }
    fun openCamera()
    {
        if(getExternalStoragePath() != "")
        {
            mFilePath = getExternalStoragePath()
        }
        else
        {
            Toast.makeText(this, "外部存储的路径返回值为空", Toast.LENGTH_SHORT).show()
            return
        }
        mFilePath = mFilePath + "/" + System.currentTimeMillis() + ".png"
        if(!isExternalStorageWritable())
        {
            Toast.makeText(this, "请检查SD卡是否可用", Toast.LENGTH_SHORT).show()
            return
        }

        mFilePath = File(mFilePath).absolutePath
        takePhotoBiggerThan7(mFilePath)
    }
    fun isExternalStorageWritable():Boolean{
        //外部存储已挂载并可读写
        return Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED
    }
    fun takePhotoBiggerThan7(absolutePath:String){
        try{
            //键值对 向媒体库中插入一条记录,以下是即将拍摄的图片存储位置的文件
            //信息
            var values = ContentValues(1)
            values.put(MediaStore.Images.Media.MIME_TYPE, "image/png")
            values.put(MediaStore.Images.Media.DATA, absolutePath)
            //插入媒体库中
            mFileUri  = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)!!
            //contentResolver会将values传递给contentProvider, Provider会根据信息创建新的记录     EXTERNAL_CONTENT_URI这是contentProvider的地址
            takePhotoLauncher.launch(mFileUri!!)
        }catch (e:Exception){
            e.printStackTrace()
        }
    }
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when(requestCode){
            1->{
                if (grantResults.isNotEmpty())
                {
                    for(result in grantResults){
                        if(result != PackageManager.PERMISSION_GRANTED)
                        {
                            Toast.makeText(this, "授权失败", Toast.LENGTH_LONG).show()
                            permissionDialog();
                            return
                        }
                    }
                }
            }
        }

    }
    //压缩bitmap
    private fun zipBitmap(original:Bitmap, ratio:Float):Bitmap?{
        val matrix = Matrix()
        //在当前矩阵基础上执行缩放操作
        matrix.preScale(ratio, ratio)
        val bitmap = Bitmap.createBitmap(original, 0, 0, original.width, original.height,matrix, false)//不进行过滤 不影响原图的画质
        return bitmap
    }

    private fun getExternalStoragePath(): String {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val appSpecificDir = getExternalFilesDir(null)
            appSpecificDir?.path?:""
            //如果appSpecificDir?.path为空 返回""
        } else {
            Environment.getExternalStorageDirectory().path
        }
    }

    // 弹出对话框用于选择
    private fun permissionDialog() {
        if (alertDialog == null) {
            alertDialog = AlertDialog.Builder(this)
                .setTitle("提示信息")
                .setMessage("当前应用缺少必要权限，该拍摄功能暂时无法使用。如若需要，请单击【设置】按钮前往设置中心进行权限授权。")
                .setPositiveButton("设置") { dialog, which ->
                    cancelPermissionDialog()
                    // package:包名前缀 告诉代码这是包的uri
                    val packageURI = Uri.parse("package:$packageName")
                    val intent =
                        // 指定打开这个packageURI应用的系统详细设置
                        Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI)
                    startActivity(intent)
                }
                .setNegativeButton(
                    "取消"
                ) { dialog, which -> cancelPermissionDialog() }
                .create()
        }
        alertDialog!!.show()
    }

    private fun cancelPermissionDialog() {
        // 取消弹出的对话框
        alertDialog!!.cancel()
    }



    fun getPermission()
    {
        val permissionList= ArrayList<String>()
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
        {
            permissionList.add(Manifest.permission.CAMERA)
        }
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
        {
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        }
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
        {
            permissionList.add(Manifest.permission.READ_EXTERNAL_STORAGE)
        }
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ){
            // 未授权，则加入到未授权列表中
            permissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION)
        }
        if(ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ){
            // 未授权，则加入到未授权列表中
            permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION)
        }
        if(ContextCompat.checkSelfPermission(this,

                Manifest.permission.ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED ){

            // 未授权，则加入到未授权列表中

            permissionList.add(Manifest.permission.ACCESS_WIFI_STATE)
        }
        if (permissionList.isNotEmpty())
        {
            ActivityCompat.requestPermissions(this, permissionList.toTypedArray(), 1)
        }
        else{
            Toast.makeText(this, "授权成功", Toast.LENGTH_LONG).show()
        }
    }
}